/**
 * Created by 11450 on 2017/3/14.
 */

module.controller('StorageManageController',
    function ($scope,$rootScope,$cookies,$q,$window,$stateParams,$http,$uibModal,storageService,k8sService,VolMgrConf,netTesting,svcCommonService) {
        var item = {
            name:$stateParams.volname,
            type:$stateParams.storageType
        };

        // console.log(item);

        if(item.name === '' || item.type === ''){
            $scope.iserror = false;
        }else{
            $scope.iserror = true;
            var loopTO = undefined;
            var isClose = false;
            var _user = $cookies.get("username");
            var volume = item;
            console.log("item.svcId--------"+item.svcId)
            var _url = "http://"+item.svcId+"."+_user+"."+VolMgrConf.service_domain+":"+VolMgrConf.service_port+"/index.php?user/loginSubmit&name=demo&check_code=undefined&password=demo&rember_password=1";
            $scope.templateUrl = '/template/cp/ngbusytemplate.html';
            var testPromise = $q.defer();
            $scope.myPromise = testPromise.promise;
            var _pingTimes = 2;
            var spin = setTimeout(function () {
                var _spin = angular.element(".spinner")
                    .fadeIn("fast")
                    .delay(1000000);
            },200);


            storageService.checkVolumeMgrService(volume.name).then(function(ret) {

                // var _volId = volume.volumeId;
                // var _self = this;
                var _url = undefined;
                //not exist to create service
                if (ret.data.ret === false) {

                    storageService.createVolumeMgrService(volume).then(function (ret) {
                            if (ret.data.ret === true) {
                              console.log("ret.data.svcId--------"+ret.data.svcId)

                              _url = "http://"+ret.data.svcId + ".default." + VolMgrConf.service_domain + ":" + VolMgrConf.service_port + "/index.php?user/loginSubmit&name=demo&check_code=undefined&password=demo&rember_password=1";
                                //_url = ret.data.svcId + ".default." + VolMgrConf.service_domain + ":" + VolMgrConf.service_port + "/index.php?user/loginSubmit&name=demo&check_code=undefined&password=demo&rember_password=1";
                                volume.svcId = ret.data.svcId;
                                _getpodst(volume.svcId);
                            }
                        }
                        , function (err) {

                        }
                    );
                }
                //start service
                else {
                    volume.svcId = ret.data.svcId;
                  console.log("ret.data.svcId---2-----"+ret.data.svcId)
                  _url = "http://"+ret.data.svcId + ".default." + VolMgrConf.service_domain + ":" + VolMgrConf.service_port + "/index.php?user/loginSubmit&name=demo&check_code=undefined&password=demo&rember_password=1";
                    //_url = ret.data.svcId + ".default." + VolMgrConf.service_domain + ":" + VolMgrConf.service_port + "/index.php?user/loginSubmit&name=demo&check_code=undefined&password=demo&rember_password=1";
                    isloop();

                    function isloop() {
                        svcCommonService.getDefaultPodStatus({app: volume.svcId },function(rets){
                            if (rets !== undefined
                                && rets.length > 0){

                                //it should be only one ,but sometime will more than one , fix in future
                                var _loop = false;
                                for(var i=0; i< rets.length ; i++){
                                    if(rets[i].phase === 'running'){
                                        _loop = true;
                                        break;
                                    }
                                }
                                if(_loop === true)
                                    _loopPing();
                                else{
                                    //pod get termination status
                                    // _startVolMgrSvc(volume.svcId);
                                    isloop();

                                }
                            } else {
                                _startVolMgrSvc(volume.svcId);

                            }
                        });

                    }



                }


                function _startVolMgrSvc(svcId){
                    storageService.startVolumeMgrService(svcId).then(function (ret) {
                        if (ret.data === true) {
                            //_loopPing(_url);
                            _getpodst(volume.svcId);
                        }
                    }, function (err) {

                    });
                }


                function _getpodst(svcId) {
                    //all loop should run in controller not
                    if (isClose === false){
                        svcCommonService.getDefaultPodStatus({app: svcId},function(rets){
                            if (rets !== undefined
                                && rets.length > 0
                                && rets[0].phase === 'running') {
                                _loopPing();
                            } else {
                                loopTO = setTimeout(_getpodst, 2500, svcId);
                            }
                        });
                    }

                }

                function _loopPing() {

                    if (isClose === false) {

                      setTimeout(function () {
                        window.location.href = _url;
                      },3000)

                /*        netTesting.reset(_url);
                        netTesting.ping(_url, function (host, ret) {
                            if (ret === 'connected') {
                                //need to req one more
                                if(_pingTimes > 1){
                                    _pingTimes--;
                                    loopTO = setTimeout(_loopPing, 2000);
                                }else{
                                    _pingTimes = 2;
                                    //$window.open(_url);
                                    console.log(_urf);
                                    testPromise.resolve();
                                }
                            }
                            else {
                                loopTO = setTimeout(_loopPing, 2000);
                            }
                        });*/
                    }
                }
            });
        }


        $scope.uploadFile = function(item){

            var modalInstance = $uibModal.open({
                animation:true ,
                templateUrl: 'template/cp/uploadFiles.html',
                controller: 'UploadFilesController',
                resolve: {
                    item: function () {
                        return item;
                    }
                }
            });

            modalInstance.result.then(function (ret) {

            }, function (err) {
                //dismiss err flow
                if(err !== 'cancel'&& err !== 'backdrop click'  ){
                    alertify.alert('upload error',err);
                }
            });

        }

        $scope.$on('$destroy', function(){
            if(loopTO !== undefined)
                clearTimeout(spin);
                clearTimeout(loopTO);
            isClose = true;
        });

    }
);